/** \file    redirect.h
  * \brief   During existance of object instance redirects std::clog events to a file or another streambuf
  * \date    2001
  * \author  Fedor Chelnokov, Pasha Agapov
  * \version $Header: /home/cscom1r4/cvsroot/cs/include/xtd/redirect.h,v 1.1 2004/11/30 13:28:15 cscom1r4 Exp $
  */

#ifndef _std_log_redirect_h_
#define _std_log_redirect_h_

#include <iostream>
#include <fstream>

class std_log_redirect {
public:
	std_log_redirect()
		: _pbuf(0) { }
	std_log_redirect(std::streambuf * pbuf)	
		: _pbuf(0) { redirect(pbuf); }
	std_log_redirect(const char * filename, std::ios::openmode mode = std::ios::out | std::ios::trunc)
		: _pbuf(0)
	{
		if (filename != 0) {
			_fbuf.open(filename, mode);
			redirect(&_fbuf);
		}
	}
	~std_log_redirect() {
		restore();
	}
	void redirect(std::streambuf * pbuf) {
		restore();
		_pbuf = std::clog.rdbuf(pbuf);
	}
	void redirect(const char * filename, std::ios::openmode mode = std::ios::out | std::ios::trunc) {
		if (filename != 0) {
			_fbuf.open(filename, mode);
			redirect(&_fbuf);
		}
	}
	void restore() {
		if (_pbuf != 0) {
			std::clog.rdbuf(_pbuf);
			_pbuf = 0;
		}
	}
private:
	std::filebuf		_fbuf;
	std::streambuf *	_pbuf;
};

#endif //_std_log_redirect_h_
